<template>
  <div class="l-rblock" style="padding-top: 56px" v-loading="loading" :element-loading-text="$t('数据加载中...')">
    <div :class="['lr-header']">
      <!-- 顶部导航栏 -->
      <top ref="top" :isNotMeuns="true" isNotUserInfo />
    </div>
    <div class="l-tab-page">
      <div class="projectItem" v-for="(item, index) in projects" :key="index">
        <div class="projectItem-text">{{ item.f_Name }}</div>
        <div class="projectItem-btns">
          <div class="projectItem-btn-dev" @click="handleDev(item)">开发</div>
          <div class="projectItem-btn-edit" @click="handleEdit(item)">编辑</div>
        </div>
        <div class="projectItem-close">
          <el-dropdown @command="handleCommand($event, item.f_Id, index)">
            <span class="el-dropdown-link">
              <i class="el-icon-more"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="Import">导入库(全部)</el-dropdown-item>
              <el-dropdown-item command="ImportNoData">导入库(结构)</el-dropdown-item>
              <el-dropdown-item command="Export">导出库</el-dropdown-item>

              <el-dropdown-item style="color: red" command="Remove" divided>删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div class="projectItem addBtn" @click="handleAdd()">
        <i class="el-icon-plus"></i>
        <div class="addbtn-text">添加项目</div>
      </div>
    </div>

    <l-dialog
      :title="formTitle"
      :visible.sync="formVisible"
      :height="480"
      @closed="handleCloseForm"
      @opened="handleOpenedForm"
      @ok="handleSave"
    >
      <div class="l-from-body">
        <el-form :model="formData" size="mini" :rules="rules" ref="form" label-width="112px">
          <el-form-item label="名称" prop="f_Name">
            <el-input v-model="formData.f_Name"></el-input>
          </el-form-item>
          <el-form-item label="数据库类型" prop="f_DbType">
            <l-select
              :clearable="false"
              @change="handleTypeChange"
              :options="optionsDbType"
              v-model="formData.f_DbType"
            ></l-select>
          </el-form-item>
          <el-form-item>
            <el-alert :closable="false" title="此处连接为框架数据库,不是代码生成器数据库！" type="warning"> </el-alert>
          </el-form-item>
          <el-form-item label="数据库连接" prop="f_DbLink">
            <el-input v-model="formData.f_DbLink" clearable>
              <el-button slot="append" @click="handleTest" :loading="testLoading">测试连接</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="后端目录" prop="f_WebApi">
            <el-input v-model="formData.f_WebApi"> </el-input>
          </el-form-item>
          <el-form-item label="前端PC目录" prop="f_PCWeb">
            <el-input v-model="formData.f_PCWeb"> </el-input>
          </el-form-item>
          <el-form-item label="移动端目录" prop="f_App">
            <el-input v-model="formData.f_App"> </el-input>
          </el-form-item>
        </el-form>
      </div>
    </l-dialog>

    <l-db-import
      dbCode="saas"
      :projectId="projectId"
      :isUpdateData="isUpdateData"
      :visible.sync="importVisible"
    ></l-db-import>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import top from "../../../../core/page/index/top/index.vue";

export default {
  components: {
    top,
  },
  data() {
    return {
      formVisible: false,
      formTitle: "",
      formEdit: false,
      formEditRow: null,
      projects: [],

      formData: {
        f_Name: "",
        f_DbType: "MySql",
        f_DbLink: "server=localhost;Database=xxx;Uid=root;Pwd=haosql;SslMode=none;",
        f_WebApi: "",
        f_PCWeb: "",
        f_App: "",
      },
      rules: {
        f_Name: [{ required: true, message: "请输入名称" }],
        f_DbLink: [{ required: true, message: "请输入数据库连接" }],
        /*f_WebApi: [
                    { required: true, message: '请输入后端目录' }
                ],
                f_PCWeb: [
                    { required: true, message: '请输入前端目录' }
                ],*/
      },
      optionsDbType: [
        { value: "MySql", label: "MySql" },
        { value: "SqlServer", label: "SqlServer" },
        { value: "Oracle", label: "Oracle" },
        { value: "PostgreSQL", label: "PostgreSQL" },
        { value: "Dameng", label: "达梦" },
        { value: "Kdbndp", label: "人大金仓" },
      ],
      link: {
        SqlServer: "server=.;uid=sa;pwd=haosql;database=xxx",
        MySql: "server=localhost;Database=xxx;Uid=root;Pwd=haosql;SslMode=none;",
        Oracle: "Data Source=localhost/orcl;User ID=system;Password=haha;",
        PostgreSQL: "PORT=5432;DATABASE=xxx;HOST=localhost;PASSWORD=haosql;USER ID=postgres",
        Dameng: "Server=localhost; User Id=SYSDBA; PWD=SYSDBA;DATABASE=xxx",
        Kdbndp: "Server=127.0.0.1;Port=54321;UID=SYSTEM;PWD=system;database=xxx",
      },

      loading: false,
      testLoading: false,

      projectId: "",
      importVisible: false,
      isUpdateData: true,
    };
  },
  mounted() {
    this.loadProject();
  },
  computed: {
    ...mapGetters(["tagWel"]),
  },
  methods: {
    async loadProject() {
      // 加载项目
      this.loading = true;
      const api = window.$api.codetool.project;
      const data = await this.$awaitWraper(api.getList());
      this.projects = data || [];
      this.loading = false;
    },
    handleAdd() {
      this.formTitle = "添加项目";
      this.formEdit = false;
      this.formVisible = true;
    },
    handleEdit(item) {
      this.formEditRow = this.$deepClone(item);
      this.formTitle = `编辑项目${item.f_Name}`;
      this.formEdit = true;
      this.formVisible = true;
    },
    handleTypeChange() {
      this.formData.f_DbLink = this.link[this.formData.f_DbType];
    },
    handleSave(showLoading, hideLoading) {
      const api = window.$api.codetool.project;
      this.$refs.form.validate((valid) => {
        if (valid) {
          showLoading();
          const formData = this.$deepClone(this.formData);
          if (this.formEdit) {
            // 修改数据
            api
              .update(formData.f_Id, formData)
              .then(() => {
                hideLoading();
                this.formVisible = false;
                this.$message({
                  type: "success",
                  message: "更新成功!",
                });
                this.loadProject();
              })
              .catch(() => {
                hideLoading();
              });
          } else {
            // 新增数据
            api
              .add(formData)
              .then(() => {
                hideLoading();
                this.formVisible = false;
                this.$message({
                  type: "success",
                  message: "添加成功!",
                });
                this.loadProject();
              })
              .catch(() => {
                hideLoading();
              });
          }
        }
      });
    },
    handleCloseForm() {
      this.formData.f_UserId = "";
      this.formData.f_Id = "";
      this.$formClear(this.$refs.form);
    },
    handleOpenedForm() {
      if (this.formEdit) {
        this.formData = this.formEditRow;
      }
    },
    handleTest() {
      const req = {
        connection: this.formData.f_DbLink,
        dbType: this.formData.f_DbType,
      };
      if (!req.connection) {
        this.$message({
          type: "error",
          message: "请填写连接串!",
        });
        return;
      }
      this.testLoading = true;
      window.$api.data.dblink
        .testNoProject(req)
        .then((res) => {
          if (res.data.data) {
            this.$message({
              type: "success",
              message: "测试成功!",
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.info,
            });
          }
          this.testLoading = false;
        })
        .catch(() => {
          this.testLoading = false;
        });
    },
    handleRemove(id, index) {
      const api = window.$api.codetool.project;
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.projects.splice(index, 1);
          api.remove(id).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDev(project) {
      this.$store.dispatch("codetool/project/set", project);
      this.$router.push({ path: this.tagWel.value });
    },

    handleExport(id) {
      this.lr_downFile(
        `data/codeTable/export/database/saas?learunprojectId=${id}`,
        "",
        {},
        "data/codeTable/export/database"
      );
    },
    handleImport(id) {
      this.projectId = id;
      this.isUpdateData = true;
      this.importVisible = true;
    },
    handleImportNoData(id) {
      this.projectId = id;
      this.isUpdateData = false;
      this.importVisible = true;
    },

    handleCommand(command, id, index) {
      const handle = this[`handle${command}`];
      handle && handle(id, index);
    },
  },
};
</script>
<style lang="scss" scoped>
.projectItem {
  box-sizing: border-box;
  position: relative;
  height: 144px;
  width: 240px;
  border-radius: 4px;
  background-color: #fff;
  float: left;
  margin: 8px;
  overflow: hidden;
}
.projectItem-text {
  font-size: 16px;
  padding: 16px 0 0 16px;
}
.addBtn {
  padding-top: 24px;
  text-align: center;
  cursor: pointer;
  font-size: 56px;
}
.addbtn-text {
  position: absolute;
  bottom: 16px;
  left: 0;
  text-align: center;
  width: 100%;
  font-size: 14px;
}

.projectItem-btns {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 32px;
  background: #4b4b4d;
  padding: 4px 0;
  box-sizing: border-box;
}
.projectItem-btn-dev,
.projectItem-btn-edit {
  position: relative;
  font-size: 14px;
  color: #d5d5d5;
  cursor: pointer;
  width: 50%;
  height: 100%;
  float: left;
  text-align: center;
  line-height: 24px;
  box-sizing: border-box;
}
.projectItem-btn-dev {
  color: #409eff;
  border-right: 1px solid #414043;
}
.projectItem-close {
  position: absolute;
  top: 4px;
  right: 8px;
  cursor: pointer;
}
</style>
